package com.xcdh.gateway.filter;

import com.xcdh.gateway.consts.StringConst;
import com.xcdh.gateway.util.JwtUtil;
import com.xcdh.gateway.config.AuthProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class AuthGlobalFilter implements GlobalFilter {
    @Autowired
    private AuthProperty authProperty ;
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if(iExcludePath(request.getPath().toString())){
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(StringConst.AUTH_KEY);
        try{
            String userInfo = JwtUtil.parseToken(token);
            exchange.mutate().request(builder->builder.header(StringConst.USER_KEY , userInfo) );
        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            Flux<String> jsonData = Flux.just("{\"msg\": \"未登录\",\"code\":401 , \"status\":false}");
            return response.writeWith(jsonData.map(s -> response.bufferFactory().wrap(s.getBytes()))) ;
        }
        return chain.filter(exchange);
    }

    private boolean iExcludePath(String path){
        for (String excludePath : authProperty.getExcludePaths()) {
            if(pathMatcher.match(excludePath , path)){
                return true ;
            }
        }
        return false ;
    }
}
